package com.gridmobi.xrtb.common;

import com.alibaba.fastjson.JSONObject;
import com.gridmobi.xrtb.domain.dsp.DspCampaigns;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class BudgetResourcePool {
    private static volatile Map<String, BudgetBasedRateLimiter> budgetBasedRateLimiterMap = new ConcurrentHashMap<>();


    public static void initLimiter(List datas) {
        if (CollectionUtils.isEmpty(datas)) {
            log.error(" campaign load error");
            return;
        }
        for (Object data : datas) {
            DspCampaigns c = JSONObject.parseObject(JSONObject.toJSONString(data), DspCampaigns.class);
            BudgetBasedRateLimiter rl = new BudgetBasedRateLimiter(c.getBudgetdaily(),c.getCurrentdailybudget(),c.getBuyingprice());
            budgetBasedRateLimiterMap.put(c.getId() + "", rl);
        }

    }

    public static  boolean tryAcquire(String cid,Float spent){

        BudgetBasedRateLimiter budgetBasedRateLimiter = budgetBasedRateLimiterMap.get(cid);
        if (budgetBasedRateLimiter == null) {
            return false;
        }
//        if (budgetBasedRateLimiter.getPerPrice() < spent) {
//            return false;
//        }

        boolean res = budgetBasedRateLimiter.tryAcquire(spent);

        return res;
    }


}
